//1. 导入 createAsyncThunk
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from 'axios';

//调用函数, 获得异步 action creator
//                                类型 字符串          函数: 完成异步任务, 返回『promise对象』
export let getHeroAction = createAsyncThunk('hero/asyncGet', async (payload) => {
  //执行异步任务
  let result = await axios.get('http://api.xiaohigh.com/heros', {
    params: {
      name_like: payload
    }
  });
  //返回结果
  return result.data;// result.data 成功时值是一个数组
});
// createAsyncThunk 返回结果『函数』


let heroSlice = createSlice({
  //别名
  name: 'hero',
  //初始值
  initialState: {
    heros: [],
    isFirst: true,
    loading: false
  },
  reducers: {
    
  },
  //用来对异步 action creator 状态进行处理的
  extraReducers: {
    //异步任务成功的回调
    [getHeroAction.fulfilled]: (state, action) => {
      //更新 hero 的状态
      state.heros = action.payload;
      //更新 isFirst 的状态
      state.isFirst = false;
      //更新 loading 的状态
      state.loading = false;
    },
    //异步任务执行中的回调
    [getHeroAction.pending]: (state, action) => {
      state.heros = [];
      state.isFirst = false;
      state.loading = true;
    }
  }
});

let heroReducer = heroSlice.reducer;

//暴露
export default heroReducer;

